<template>
  <transition>
    <div class="upload-image">
      <div class="image" v-if="image">
        <img :src="image" />
        <div class="close" @click="image=undefined">
          <i class="el-icon-close"></i>
        </div>
      </div>
      <div v-else class="upload">
        <el-upload
          :show-file-list="false"
          action="https://jsonplaceholder.typicode.com/posts/"
          list-type="picture-card"
          :http-request="uploadRequest"
          :file-list="fileList"
          :before-upload="beforeUpload"
          :on-success="onSuccess"
          :on-error="onError"
          :limit="limit"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
      </div>
    </div>
  </transition>
</template>

<script>
import { ossUpload } from "../FileUpload/oss";

export default {
  props: {
    src: {
      type: String,
      default: undefined
    },
    limit: {
      type: Number,
      default: 1
    }
  },
  watch: {
    src() {
      this.image = this.src;
      console.log("image update src", this.src);
    }
  },
  data() {
    return {
      image: undefined,
      fileList: []
    };
  },
  mounted() {
    console.log("images", this.src);

    this.image = this.src;
  },
  methods: {
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return true;
    },
    async uploadRequest(option) {
      ossUpload(option);
    },
    onExceed(file, fileList) {
      this.$message.error("一次最多只能选择5个文件");
    },
    onSuccess(response, file, fileList) {
      if (response) {
        this.handleSuccess("http://img.ka.hiapi.cn/" + response.name);
      }
    },
    onError(error) {
      console.log("上传出现了错误,", error);
      this.$message.error(error.message);
    },

    handleSuccess(src) {
      console.log("选择成功了");
      this.image = src;
      this.$emit("success", src);
    }
  }
};
</script>

<style lang="stylus">
.upload-image {
  .el-upload--picture-card, .el-upload-list__item {
    width: 100px;
    height: 100px;
  }

  .el-upload--picture-card {
    line-height: 100px;
  }

  .image {
    background-color: #fbfdff;
    border: 1px dashed #c0ccda;
    border-radius: 6px;
    position: relative;
    width: 100px;
    height: 100px;
    padding: 3px;

    .close {
      position: absolute;
      top: -10px;
      right: 0;
      color: red;
      font-weight: bold;
      cursor: pointer;
    }
  }

  img {
    width: 100%;
    height: 100%;
  }

  .upload {
    width: 100px;
    color: #ccc;
    text-align: center;
  }
}
</style>